const router = require('koa-router')()
const {join} = require('path')
const fse = require('fs-extra')
const fs = require('fs')
const {getImagesCount,getImagesByPage,insertImages,deleteFileByID} = require('../models/images.js')


router.get('/list',async (ctx,next) => {
  const {page,limit} = ctx.query;

  if(!page) {
    ctx.body = await getImagesCount();
  }else{
    ctx.body = await getImagesByPage(page,limit);
  }
})

router.post('/images',async (ctx,next) => {
  const fileList = ctx.request.files.file;
  
  if(fileList.length > 1) {
    for(let file of fileList) {
      var {originalFilename,filepath,lastModifiedDate,mimetype} = file;

      const newPath = join(__dirname,'../public/images',originalFilename);
      await fse.move(filepath,newPath);

      let imgPath = ctx.origin + '/images/' + originalFilename;

      insertImages(imgPath,originalFilename,lastModifiedDate);
    }
  }else{
    var {originalFilename,filepath,lastModifiedDate,mimetype} = fileList;

    const newPath = join(__dirname,'../public/images',originalFilename);

    await fse.move(filepath,newPath);

    let imgPath = ctx.origin + '/images/' + originalFilename;

    insertImages(imgPath,originalFilename,lastModifiedDate);
  }

  ctx.body = '上传成功！';
})

router.delete('/delete/:id',async (ctx,next) => {
  const {id} = ctx.params;

  let fileName = await deleteFileByID(id);
  fs.rmSync(join(__dirname,'../public/images',fileName[0][0].image_name));

  ctx.body = 'ok';
})

module.exports = router
